export const toCamelCase = str => {
	str = str?.replace(/[-_\s]+(.)?/g, (match, g) => g ? g.toUpperCase() : '')
	return str ? str[0].toUpperCase() + str.substr(1) : ''
}
export const getTemplateData = ({ cols, table_name, template, table_comment }) => {
	let back_col = ''
	let back_name = ''
	console.log(cols)
	cols.forEach(({ label, name, data_type, len, not_null, key, auto_increment, def, extra }, i)=>{
		let t = data_type
		if( len && !data_type.includes('()') ){
			if( data_type === 'decimal_len' ) t = data_type + '(' + len + ', 2)'
			else t = data_type + '(' + len + ')'
		}
		table_name = toCamelCase(table_name)
		let col_name = toCamelCase(name)
		let back_col_temp = `
.col( ColumnDef::new(${ table_name }::${ col_name })
${ t ? '.' + t : '' }
${ not_null ? '.not_null()' : '' }
${ auto_increment ? '.auto_increment()' : '' }
${ key ? '.' + key : '' }
${ def!==undefined ? '.default(' + def + ')' : '' }
${ extra ? '.extra("' + extra + '")' : '' }
${ label ? '.comment("' + label + '")' : '' }
 )`
		back_col += back_col_temp.replace(/\n/g,'')  + (( i === cols.length - 1 ) ? '\t\t\t\t' : '\n\t\t\t\t')
		back_name +=  col_name +  (( i === cols.length - 1 ) ? '\t' : ',\n\t')
		
	})
	
	// 表模板
	template = template.replace(/%table_name%/g, table_name)
	template = template.replace(/%table_comment%/g, table_comment ? `.comment("${table_comment}")` : '')
	template = template.replace(/%#%/g, back_col)
	template = template.replace(/%\$%/g, back_name)
	
	return template
}

export const getBackData = ({ cols, is_tab }) => {
	let column = ''
	let model = ''
	let column_arr = []
	let model_arr = []
	let tab = is_tab ? '\t\t' : ''
	cols.forEach(({ name, data_type, not_null })=>{
		if( !['create_user', 'update_user', 'create_time', 'update_time'].includes(name) ) {
			let col_name = toCamelCase(name)
			column_arr.push( 'Column::'+ col_name )
			if( name === 'id' ) return
			// model
			let m = null
			if( ['char()','char_len','string()','string_len', 'text()'].includes(data_type) ){
				m = `${name} : Set( query::str${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type.includes('blob') || data_type.includes('blob') || data_type === 'uuid'){
				m = `${name} : Set( query::blob${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'integer()'){
				m = `${name} : Set( query::i32${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'unsigned()'){
				m = `${name} : Set( query::u32${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'tiny_integer()' || data_type === 'boolean()'){
				m = `${name} : Set( query::i8${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'tiny_unsigned()'){
				m = `${name} : Set( query::u8${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'small_integer()'){
				m = `${name} : Set( query::i16${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'samll_unsigned()'){
				m = `${name} : Set( query::u16${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'big_integer()'){
				m = `${name} : Set( query::i64${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'big_unsigned()'){
				m = `${name} : Set( query::u64${ not_null ? '' : '_op' }(&body, "${ name }")? )` 
			}else if( data_type === 'decimal_len'){
				m = `${name} : Set( query::dec${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'float()'){
				m = `${name} : Set( query::f32${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'double()'){
				m = `${name} : Set( query::f64${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type.includes('json')){
				m = `${name} : Set( query::json${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'date()'){
				m = `${name} : Set( query::date${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'date_time()'){
				m = `${name} : Set( query::date_time${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'timestamp()'){
				m = `${name} : Set( query::date_time_utc${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}else if( data_type === 'time()'){
				m = `${name} : Set( query::time${ not_null ? '' : '_op' }(&body, "${ name }")? )`
			}
			if(m) model_arr.push( tab +  m)
		}
	})
	
	column = column_arr.join(', ')
	model = model_arr.join(',\n') + ','
	return { column, model }
}

export const getTemplateFileData = ({ cols, table_name, template }) => {
	const { column, model } = getBackData({ cols, is_tab:1 })
	template = template.replace(/%table_name%/g, table_name)
	template = template.replace(/%\*%/g, column)
	template = template.replace(/%#%/g, model)
	return template
}

export const getFrontData = ({ cols, is_tab }) => {
	let form_arr = []
	let table_arr = []
	let tab = is_tab ? '\t\t\t\t' : ''
	cols.forEach(({ label, name, form_type, r, half, front })=>{
		//
		if( ![ 'id', 'uuid', 'create_user', 'update_user', 'create_time', 'update_time'].includes(name) ){
			form_arr.push({ label, name, type:form_type, r, half, ...front })
			let ellipsis
			let width = 100
			if(['textarea'].includes(form_type)){
				ellipsis = 1
				width = null
			}
			table_arr.push({ title:label, dataIndex: name, ellipsis, width })
		}
	})
	// 表单
	form_arr = form_arr.map( v => {
		let stack = []
		for( let i in v){
			if(v[i] !== undefined && v[i] !== null){
				stack[i] = v[i]
			}
		}
		return stack
	})
	let form_str = ''
	form_arr.forEach( (v,t) => {
		let str = ''
		let k = 0
		for( let i in v){
			k ++
			str += `${i}: ` + ( typeof v[i] === 'string' ? `'${v[i]}'` : v[i] ) + ( k === Object.keys(v).length ? '' : ', ' )
		}
		form_str += tab + '{ ' + str + ' }' + ( t === form_arr.length -1 ? '' : ',\n' )
	})
	
	// 表格
	table_arr  = table_arr.map( v => {
		let stack = {}
		for( let i in v){
			if(v[i] !== undefined && v[i] !== null){
				stack[i] = v[i]
			}
		}
		return stack
	})
	
	let table_str = ''
	table_arr.forEach( (v,t) => {
		let str = ''
		let k = 0
		for( let i in v){
			k ++
			str += `${i}: ` + ( typeof v[i] === 'string' ? `'${v[i]}'` : v[i] ) + ( k === Object.keys(v).length ? '' : ', ' )
		}
		table_str += tab + '{ ' + str + ' }' + ( t === table_arr.length -1 ? '' : ',\n' )
	})
	
	return { form_str, table_str }
}

export const getFrontTemplateData = ({ cols, template }) => {
	const { form_str, table_str } = getFrontData({ cols, is_tab:1 })
	template = template.replace(/%\*%/g, table_str)
	template = template.replace(/%#%/g, form_str)
	return template
}

export default { getTemplateFileData, getFrontTemplateData }